package com.ruoyi.web.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ChatUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AiMessage;
import com.ruoyi.system.domain.AiScheme;
import com.ruoyi.system.domain.vo.AiMessageReqVo;
import com.ruoyi.system.domain.vo.AiMessageVo;
import com.ruoyi.system.domain.vo.AiSchemeVo;
import com.ruoyi.system.domain.vo.MessageVo;
import com.ruoyi.system.service.IAiMessageService;
import com.ruoyi.system.service.IAiSchemeService;
import com.ruoyi.web.service.ChatBankService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户会话信息-对外API接口请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/message")
public class ApiAiMessageController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(ApiAiMessageController.class);
    @Autowired
    private IAiMessageService messageService;
    @Autowired
    private IAiSchemeService schemeService;
    @Autowired
    private ChatBankService chatBankService;

    @Log(title = "【Chat消息】", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增chat消息")
    public AjaxResult add(@RequestBody AiMessage message) {
        message.setUserId(getUserId());
        return AjaxResult.success(messageService.insertAiMessage(message));
    }

    @Transactional
    @Log(title = "【AI生成方案】", businessType = BusinessType.INSERT)
    @PostMapping(value = "/gpt")
    @ApiOperation(value = "新增chat消息通过fast-gpt生成方案内容")
    public AjaxResult gpt(@RequestBody AiMessageReqVo req) {
        // 调用fast-gpt，分析产生方案内容，有则保存方案
        if (null == req) return AjaxResult.error("参数不能为空");

        // Chat消息上传，如果之前已经存在，则先删除，再插入
        List<MessageVo> messageVos = req.getMessages();
        if (messageVos.isEmpty()) return AjaxResult.error("Chat消息不能为空");
        AiMessage query = new AiMessage();
        query.setUserId(getUserId());
        query.setSessionId(req.getSessionId());
        query.setTopicId(req.getTopicId());
        List<AiMessage> list = messageService.selectAiMessageList(query);
        if (CollUtil.isNotEmpty(list)) {
            List<String> ids = list.stream().map(AiMessage::getId).collect(Collectors.toList());
            messageService.deleteAiMessageByIds(ids.toArray(new String[0]));
        }
        // 插入消息，同时组装下请求fast-gpt参数
        List<Map<String, Object>> messages = new ArrayList<>();
        for (MessageVo message : messageVos) {
            AiMessage aiMessage = new AiMessage();
            aiMessage.setUserId(getUserId());
            aiMessage.setSessionId(req.getSessionId());
            aiMessage.setTopicId(req.getTopicId());
            aiMessage.setContent(message.getContent());
            aiMessage.setRole(message.getRole());
            messageService.insertAiMessage(aiMessage);
            // 添加会话消息，去请求fast-gpt
            messages.add(ChatUtils.message(message.getRole(), message.getContent()));
        }

        // 构建请求体
        Map<String, Object> data = new HashMap<>();
        data.put("chatId", "");
        data.put("stream", false);
        data.put("detail", false);
        data.put("messages", messages);

        // 对于fast-gpt返回的content, 是否能转成JSON，能则解析用户的商机，保存下来，否则不管
        String content = ChatUtils.requestChatScheme(data);
        if (StrUtil.isBlank(content)) {
            return AjaxResult.error(HttpStatus.NOT_CREATE_SCHEME, "未生成方案");
        }
        AiScheme aiScheme = new AiScheme();
        aiScheme.setUserId(getUserId());
        aiScheme.setTitle("最新方案");
        aiScheme.setDescription("方案正在完善中");
        aiScheme.setContent(content);
        aiScheme.setSessionId(req.getSessionId());
        aiScheme.setTopicId(req.getTopicId());
        schemeService.insertAiScheme(aiScheme);
        // 返回方案信息
        AiScheme scheme = schemeService.selectAiSchemeById(aiScheme.getId());
        AiSchemeVo resp = new AiSchemeVo();
        BeanUtil.copyProperties(scheme, resp);
        // 完善方案信息，异步执行
        chatBankService.requestFillChatScheme(scheme);
        log.info("===================");
        return AjaxResult.success(resp);
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询chat消息列表")
    public AjaxResult list(@RequestParam(value = "sessionId", required = false) String sessionId,
                           @RequestParam(value = "topicId", required = false) String topicId) {
        AiMessage message = new AiMessage();
        message.setSessionId(sessionId);
        message.setTopicId(topicId);
        message.setUserId(hasLoginUser());
        List<AiMessage> list = messageService.selectAiMessageList(message);
        if (CollUtil.isEmpty(list)) return AjaxResult.success(new ArrayList<>());
        return AjaxResult.success(list.stream().map(this::changeItem).collect(Collectors.toList()));
    }

    private AiMessageVo changeItem(AiMessage message) {
        if (null == message) return null;
        AiMessageVo resp = new AiMessageVo();
        BeanUtil.copyProperties(message, resp);
        return resp;
    }
}
